package com.customer.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.ContainerProvider;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import com.customer.properties.AlProperties;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.customer.dto.AITextRequestDTO;
import com.customer.entity.AIMessage;
import com.customer.entity.AISession;
import com.customer.model.tts.RelayTTSResponse;
import com.customer.model.tts.TTSRequest;
import com.customer.service.AIService;
import com.customer.service.AISessionService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class StreamingChatHandler extends TextWebSocketHandler {
    // 存储配置信息的实例字段
    private final String QINIU_AI_TTS_WSS_URL;
    private final String QINIU_AI_LLM_API_URL;
    private final String QINIU_AI_TOKEN;
    
    // 存储客户端会话
    private final Map<String, WebSocketSession> clientSessions = new ConcurrentHashMap<>();
    
    private final AIService aiService;
    private final AISessionService aiSessionService;
    
    // 构造函数注入
    @Autowired
    public StreamingChatHandler(AlProperties alProperties, AIService aiService, AISessionService aiSessionService) {
        this.QINIU_AI_TTS_WSS_URL = alProperties.getTts();
        this.QINIU_AI_LLM_API_URL = alProperties.getLlm();
        this.QINIU_AI_TOKEN = alProperties.getToken();
        this.aiService = aiService;
        this.aiSessionService = aiSessionService;
    }

    /**
     * WebSocket连接建立后的回调方法
     *
     * @param session WebSocket会话对象，包含连接信息和通信方法
     * @throws Exception 当连接处理过程中发生错误时抛出
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("客户端WebSocket连接已建立: {}", session.getId());
        clientSessions.put(session.getId(), session);
        // 发送连接成功消息
        JSONObject welcomeMsg = new JSONObject();
        welcomeMsg.put("type", "connected");
        welcomeMsg.put("message", "WebSocket连接成功，可以开始发送消息");
        session.sendMessage(new TextMessage(welcomeMsg.toJSONString()));
    }

    /**
     * 处理 WebSocket 接收到的文本消息。
     *
     * @param session WebSocket 会话对象，用于与客户端通信
     * @param message 客户端发送的文本消息对象，包含具体的消息内容
     * @throws Exception 处理过程中可能抛出的异常
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String clientMessage = message.getPayload();
        log.info("收到客户端消息: {}", clientMessage);
        try {
            JSONObject msgObj = JSON.parseObject(clientMessage);
            String type = msgObj.getString("type");
            switch (type) {
                case "chat":
                case "text_message": // 新增支持text_message类型
                    // 处理聊天请求
                    String text = msgObj.getString("text");
                    String sessionId = msgObj.getString("sessionId");
                    Long userId = msgObj.getLong("userId");
                    String character = msgObj.getString("character");
                    String voiceId = msgObj.getString("voiceId");
                    String prompt = msgObj.getString("prompt");
                    // 检查会话是否存在，如果不存在则创建
                    AISession aiSession = aiSessionService.getSessionBySessionId(sessionId);
                    if (aiSession == null) {
                        aiSession = aiSessionService.createSession(userId, character, text);
                        sessionId = aiSession.getSessionId();
                    }
                    // 异步处理流式回复，传递voiceId和prompt参数
                    handleStreamingChat(session, userId, sessionId, text, aiSession.getId(), voiceId, prompt);
                    break;
                case "voice_chat":
                    // 处理语音聊天请求
                    String filePath = msgObj.getString("filePath");
                    String voiceSessionId = msgObj.getString("sessionId");
                    Long voiceUserId = msgObj.getLong("userId");
                    String voiceChatVoiceId = msgObj.getString("voiceId");
                    String voiceChatPrompt = msgObj.getString("prompt");
                    handleStreamingVoiceChat(session, voiceUserId, voiceSessionId, filePath, voiceChatVoiceId, voiceChatPrompt);
                    break;
                case "config": // 新增支持config类型
                    // 接收配置信息并返回确认
                    log.info("收到配置信息: {}", msgObj.getJSONObject("config"));
                    JSONObject configReply = new JSONObject();
                    configReply.put("type", "config_ack");
                    configReply.put("message", "配置已接收");
                    session.sendMessage(new TextMessage(configReply.toJSONString()));
                    break;
                case "audio": // 新增支持audio类型
                    // 添加音频数据处理逻辑
                    String audioData = msgObj.getString("audio");
                    log.debug("收到音频数据，长度: {}", audioData.length());
                    break;
                case "end_audio": // 新增支持end_audio类型
                    // 音频发送结束，开始处理
                    String endAudioSessionId = msgObj.getString("sessionId");
                    Long endAudioUserId = msgObj.getLong("userId");
                    prompt = msgObj.getString("prompt");
                    log.info("音频发送结束，准备处理: sessionId={}", endAudioSessionId);
                    String mockText = "我收到了您的语音消息，这是我的回复。";
                    // 获取或创建会话，添加dbSessionId参数
                    AISession endAudioAISession = aiSessionService.getSessionBySessionId(endAudioSessionId);
                    if (endAudioAISession == null) {
                        endAudioAISession = aiSessionService.createSession(endAudioUserId, "default", mockText);
                        endAudioSessionId = endAudioAISession.getSessionId();
                    }
                    // 添加默认voiceId参数
                    String defaultVoiceId = "qiniu_zh_male_hlsnkk";
                    handleStreamingChat(session, endAudioUserId, endAudioSessionId, mockText, endAudioAISession.getId(), defaultVoiceId, prompt);

                    break;
                default:
                    log.warn("未知消息类型: {}", type);
                    break;
            }
        } catch (Exception e) {
            log.error("处理客户端消息失败", e);
            sendErrorMessage(session, "处理消息失败: " + e.getMessage());
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("客户端WebSocket连接已关闭: {}, 状态: {}", session.getId(), status);
        clientSessions.remove(session.getId());
    }

    /**
     * 处理流式文字对话
     */
    private void handleStreamingChat(WebSocketSession session, Long userId, String sessionId, String text, Long dbSessionId, String voiceId, String prompt) {
        new Thread(() -> {
            try {
                // 保存用户消息
                AIMessage userMessage = AIMessage.builder()
                        .sessionId(dbSessionId)
                        .userId(userId)
                        .role(0) // 0表示用户
                        .content(text)
                        .sendTime(LocalDateTime.now())
                        .messageType(0) // 0表示文本
                        .build();
                aiSessionService.saveMessage(userMessage);
                // 构造AI请求参数
                AITextRequestDTO requestDTO = new AITextRequestDTO();
                requestDTO.setUserId(userId);
                requestDTO.setSessionId(sessionId);
                requestDTO.setText(text);
                requestDTO.setDbSessionId(dbSessionId);
                requestDTO.setVoiceId(voiceId);
                requestDTO.setPrompt(prompt);
                // 发送开始处理消息
                sendStartProcessingMessage(session);
                // 执行流式请求
                performStreamingRequest(session, requestDTO);
            } catch (Exception e) {
                log.error("流式对话处理失败", e);
                sendErrorMessage(session, "AI处理失败: " + e.getMessage());
            }
        }).start();
    }

    /**
     * 处理流式语音对话
     */
    private void handleStreamingVoiceChat(WebSocketSession session, Long userId, String sessionId, String filePath, String voiceId, String prompt) {
        new Thread(() -> {
            try {
                // 发送开始处理消息
                sendStartProcessingMessage(session);

                // 1. 语音识别 (ASR)
                sendStatusMessage(session, "正在进行语音识别...");
                String recognizedText = aiService.doASRByFilePath(filePath);

                if (recognizedText == null || recognizedText.trim().isEmpty()) {
                    sendErrorMessage(session, "语音识别失败，请重试");
                    return;
                }

                // 发送识别结果
                JSONObject asrResult = new JSONObject();
                asrResult.put("type", "asr_result");
                asrResult.put("text", recognizedText);
                session.sendMessage(new TextMessage(asrResult.toJSONString()));

                // 2. 检查会话是否存在，如果不存在则创建
                String currentSessionId = sessionId;
                AISession aiSession = aiSessionService.getSessionBySessionId(currentSessionId);
                if (aiSession == null) {
                    aiSession = aiSessionService.createSession(userId, "default", recognizedText);
                    currentSessionId = aiSession.getSessionId();
                }
                Long dbSessionId = aiSession.getId();

                // 3. 保存用户语音消息（使用识别后的文本）
                AIMessage userMessage = AIMessage.builder()
                        .sessionId(dbSessionId)
                        .userId(userId)
                        .role(0) // 0表示用户
                        .content(recognizedText)
                        .sendTime(LocalDateTime.now())
                        .messageType(1) // 1表示语音
                        .build();
                aiSessionService.saveMessage(userMessage);

                // 4. 执行流式AI对话
                sendStatusMessage(session, "正在获取AI回复...");
                AITextRequestDTO requestDTO = new AITextRequestDTO();
                requestDTO.setUserId(userId);
                requestDTO.setSessionId(currentSessionId); // 使用临时变量
                requestDTO.setText(recognizedText);
                requestDTO.setDbSessionId(dbSessionId); // 确保设置数据库会话ID
                requestDTO.setVoiceId(voiceId);
                requestDTO.setPrompt(prompt);
                performStreamingRequest(session, requestDTO);

            } catch (Exception e) {
                log.error("流式语音对话处理失败", e);
                sendErrorMessage(session, "语音对话处理失败: " + e.getMessage());
            }
        }).start();
    }

    /**
     * 执行流式AI请求
     */
    private void performStreamingRequest(WebSocketSession session, AITextRequestDTO requestDTO) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(QINIU_AI_LLM_API_URL);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + QINIU_AI_TOKEN);

            // 构建请求体
            List<Map<String, String>> messages = new ArrayList<>();

            // 如果有角色提示词，添加为系统消息
            if (requestDTO.getPrompt() != null && !requestDTO.getPrompt().isEmpty()) {
                Map<String, String> systemMessage = new HashMap<>();
                systemMessage.put("role", "system");
                systemMessage.put("content", requestDTO.getPrompt());
                messages.add(systemMessage);
            }

            // 获取会话历史消息
            if (requestDTO.getDbSessionId() != null) {
                List<AIMessage> sessionMessages = aiSessionService.getSessionMessages(requestDTO.getDbSessionId());
                // 添加历史消息到messages列表
                for (AIMessage msg : sessionMessages) {
                    Map<String, String> historyMessage = new HashMap<>();
                    historyMessage.put("role", msg.getRole() == 0 ? "user" : "assistant");
                    historyMessage.put("content", msg.getContent());
                    messages.add(historyMessage);
                }
            }

            // 添加当前用户消息
            Map<String, String> currentMessage = new HashMap<>();
            currentMessage.put("role", "user");
            currentMessage.put("content", requestDTO.getText());
            messages.add(currentMessage);

            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "deepseek-v3");
            requestBody.put("messages", messages);
            requestBody.put("stream", true);
            requestBody.put("max_tokens", 4096);
            // 将会话ID传递给LLM
            requestBody.put("session_id", requestDTO.getSessionId());

            // 设置请求体
            StringEntity entity = new StringEntity(requestBody.toString(), StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new Exception("API调用失败: " + response.getStatusLine().getReasonPhrase());
                }

                // 用于累积文本
                StringBuilder accumulatedText = new StringBuilder();
                // 用于TTS的文本分段处理
                AtomicReference<String> pendingTextRef = new AtomicReference<>("");
                // 用于管理TTS WebSocket会话
                final Session[] ttsSessionRef = new Session[1];
                final CountDownLatch ttsLatch = new CountDownLatch(1);

                // 保存客户端会话的引用到final变量
                final WebSocketSession finalClientSession = session;

                // 初始化TTS WebSocket连接
                try {
                    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
                    container.setDefaultMaxTextMessageBufferSize(1024 * 1024 * 5); // 5MB
                    container.setDefaultMaxBinaryMessageBufferSize(1024 * 1024 * 5); // 5MB
                    URI ttsUri = new URI(QINIU_AI_TTS_WSS_URL);

                    // 获取voiceId，如果不存在则使用默认值
                    String voiceId = requestDTO.getVoiceId() != null && !requestDTO.getVoiceId().isEmpty()
                            ? requestDTO.getVoiceId()
                            : "qiniu_zh_male_hlsnkk";

                    ClientEndpointConfig ttsConfig = ClientEndpointConfig.Builder.create()
                            .configurator(new ClientEndpointConfig.Configurator() {
                                @Override
                                public void beforeRequest(Map<String, List<String>> headers) {
                                    headers.put("Authorization", Collections.singletonList("Bearer " + QINIU_AI_TOKEN));
                                    headers.put("VoiceType", Collections.singletonList(voiceId));
                                }
                            })
                            .build();

                    // 连接TTS WebSocket服务器
                    Session ttsSession = container.connectToServer(new Endpoint() {
                        @Override
                        public void onOpen(Session session, EndpointConfig config) {
                            ttsSessionRef[0] = session;
                            try {
                                // 使用具体的MessageHandler.Whole<String>类型
                                session.addMessageHandler(new MessageHandler.Whole<String>() {
                                    @Override
                                    public void onMessage(String message) {
                                        try {
                                            // 解析TTS响应
                                            RelayTTSResponse ttsResponse = JSON.parseObject(message, RelayTTSResponse.class);

                                            // 发送音频片段到客户端
                                            JSONObject audioMsg = new JSONObject();
                                            audioMsg.put("type", "audio_segment");
                                            audioMsg.put("audioData", ttsResponse.getData());
                                            audioMsg.put("sequence", ttsResponse.getSequence());
                                            // 使用保存的客户端会话引用
                                            StreamingChatHandler.this.sendMessageToClient(finalClientSession, audioMsg.toJSONString());

                                            // 检查是否为最后一包数据
                                            if (ttsResponse.getSequence() < 0) {
                                                ttsLatch.countDown();
                                            }
                                        } catch (Exception e) {
                                            log.error("处理TTS响应失败", e);
                                            ttsLatch.countDown();
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                log.error("注册TTS消息处理器失败", e);
                                ttsLatch.countDown();
                            }
                        }
                    }, ttsConfig, ttsUri);

                    // 处理流式响应
                    try (BufferedReader reader = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            // 处理SSE格式的响应
                            if (line.startsWith("data: ")) {
                                String data = line.substring(6);
                                if (data.equals("[DONE]")) {
                                    // 发送最后一段待处理的文本到TTS
                                    String finalPendingText = pendingTextRef.get();
                                    if (!finalPendingText.isEmpty()) {
                                        // 修改断句策略，使用更智能的断句算法
                                        // 当累积足够的文本，或者遇到合适的断句点时，发送到TTS
                                        if (shouldSendToTTS(finalPendingText)) {  // 修复：使用正确的变量名
                                            // 修复：添加voiceId参数，从requestDTO中获取
                                            sendTextToTTS(ttsSession, finalPendingText, voiceId);  // 修复：使用正确的变量名
                                            pendingTextRef.set("");
                                        } else {
                                            pendingTextRef.set(finalPendingText);  // 修复：使用正确的变量名
                                        }
                                    }

                                    // 保存完整的AI回复到数据库
                                    if (!accumulatedText.toString().isEmpty()) {
                                        AIMessage aiMessage = AIMessage.builder()
                                                .sessionId(requestDTO.getDbSessionId())
                                                .userId(requestDTO.getUserId())
                                                .role(1) // 1表示AI
                                                .content(accumulatedText.toString())
                                                .sendTime(LocalDateTime.now())
                                                .messageType(0) // 0表示文本
                                                .build();
                                        aiSessionService.saveMessage(aiMessage);
                                    }

                                    break;
                                }

                                try {
                                    JSONObject json = JSON.parseObject(data);
                                    JSONArray choices = json.getJSONArray("choices");
                                    if (choices != null && !choices.isEmpty()) {
                                        JSONObject choice = choices.getJSONObject(0);
                                        JSONObject delta = choice.getJSONObject("delta");
                                        if (delta.containsKey("content")) {
                                            String textChunk = delta.getString("content");

                                            // 发送增量文本到客户端 - 修改为使用更安全的sendMessageToClient方法
                                            JSONObject responseMsg = new JSONObject();
                                            responseMsg.put("type", "stream_text");
                                            responseMsg.put("text", preprocessText(textChunk));
                                            sendMessageToClient(session, responseMsg.toJSONString());

                                            // 累积文本
                                            accumulatedText.append(textChunk);
                                            String currentPendingText = pendingTextRef.get() + textChunk;

                                            // 当累积足够的文本，或者遇到合适的断句点时，发送到TTS
                                            if (shouldSendToTTS(currentPendingText)) {
                                                sendTextToTTS(ttsSession, currentPendingText, voiceId);
                                                pendingTextRef.set("");
                                            } else {
                                                pendingTextRef.set(currentPendingText);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    log.warn("解析响应行失败: {}", line, e);
                                }
                            }
                        }
                    }

                    // 等待TTS完成
                    ttsLatch.await(30, TimeUnit.SECONDS);

                    // 关闭TTS会话
                    if (ttsSession != null && ttsSession.isOpen()) {
                        try {
                            ttsSession.close();
                        } catch (IOException e) {
                            log.warn("关闭TTS WebSocket连接失败", e);
                        }
                    }
                } catch (Exception e) {
                    log.error("初始化TTS连接失败", e);
                    // 即使TTS失败，也要继续文本流式处理
                }

                // 发送完成消息
                JSONObject completeMsg = new JSONObject();
                completeMsg.put("type", "complete");
                session.sendMessage(new TextMessage(completeMsg.toJSONString()));

            } catch (Exception e) {
                log.error("执行流式AI请求失败", e);
                throw e;
            }
        }
    }

    /**
     * 发送文本到TTS服务
     */
    private void sendTextToTTS(Session ttsSession, String text, String voiceId) {
        try {
            if (ttsSession != null && ttsSession.isOpen()) {
                // 预处理文本
                String processedText = preprocessText(text);
                if (processedText.isEmpty()) {
                    return;
                }

                // 使用传入的voiceId，如果为空则使用默认值
                String finalVoiceId = voiceId != null && !voiceId.isEmpty()
                        ? voiceId
                        : "qiniu_zh_male_hlsnkk";

                // 构建TTS请求参数
                TTSRequest ttsRequest = new TTSRequest();
                TTSRequest.Audio audio = new TTSRequest.Audio();
                audio.setVoice_type(finalVoiceId);
                audio.setEncoding("mp3");

                // 动态调整语速：长句子可以稍微快一点，短句子可以稍微慢一点
                double speedRatio = 1.0;
                if (processedText.length() > 30) {
                    speedRatio = 1.1; // 长句子稍快
                } else if (processedText.length() < 10) {
                    speedRatio = 0.9; // 短句子稍慢
                }
                audio.setSpeed_ratio(speedRatio);

                TTSRequest.Request req = new TTSRequest.Request();
                req.setText(processedText);

                ttsRequest.setAudio(audio);
                ttsRequest.setRequest(req);

                // 发送TTS请求
                String requestJson = JSON.toJSONString(ttsRequest);
                ttsSession.getBasicRemote().sendText(requestJson);
                log.info("发送文本到TTS服务: {}", text.length() > 50 ? text.substring(0, 50) + "..." : text);
            }
        } catch (Exception e) {
            log.error("发送文本到TTS服务失败", e);
        }
    }

    // 发送错误消息
    private void sendErrorMessage(WebSocketSession session, String message) {
        try {
            if (session.isOpen()) {
                JSONObject errorMsg = new JSONObject();
                errorMsg.put("type", "error");
                errorMsg.put("message", message);
                session.sendMessage(new TextMessage(errorMsg.toJSONString()));
            }
        } catch (IOException e) {
            log.error("发送错误消息失败", e);
        }
    }

    // 发送状态消息
    private void sendStatusMessage(WebSocketSession session, String message) throws IOException {
        if (session.isOpen()) {
            JSONObject statusMsg = new JSONObject();
            statusMsg.put("type", "status");
            statusMsg.put("message", message);
            session.sendMessage(new TextMessage(statusMsg.toJSONString()));
        }
    }

    // 发送开始处理消息
    private void sendStartProcessingMessage(WebSocketSession session) throws IOException {
        if (session.isOpen()) {
            JSONObject startMsg = new JSONObject();
            startMsg.put("type", "start_processing");
            session.sendMessage(new TextMessage(startMsg.toJSONString()));
        }
    }

    // 向客户端发送消息
    private void sendMessageToClient(WebSocketSession clientSession, String message) {
        try {
            if (clientSession != null && clientSession.isOpen()) {
                clientSession.sendMessage(new TextMessage(message));
                log.debug("发送消息到客户端: {}", message.length() > 100 ? message.substring(0, 100) + "..." : message);
            }
        } catch (IOException e) {
            log.error("发送消息到客户端失败", e);
        }
    }

    /**
     * 判断是否应该将当前文本发送到TTS服务
     * 优化断句策略，考虑中文语法结构
     */
    private boolean shouldSendToTTS(String text) {
        if (text == null || text.isEmpty()) {
            return false;
        }

        // 预处理文本，移除多余空格和控制字符
        String processedText = preprocessText(text);

        // 1. 如果达到一定长度(如15-20个字符)，考虑断句
        if (processedText.length() > 20) {
            return true;
        }

        // 2. 优先在句号、问号、感叹号处断句(完整句子)
        if (processedText.contains("。") || processedText.contains("？") ||
                processedText.contains("！") || processedText.contains(".") ||
                processedText.contains("?") || processedText.contains("!")) {
            return true;
        }

        // 3. 对于逗号、分号等，仅当文本长度超过一定值时才断句
        if ((processedText.contains(",") || processedText.contains("，") ||
                processedText.contains(":") || processedText.contains("：")) &&
                processedText.length() > 15) {
            return true;
        }

        // 4. 针对中文特定表达的断句优化 - 解决"有什么"等表达无法正常断句的问题
        if (processedText.contains("有什么") || processedText.contains("什么") ||
                processedText.contains("请问") || processedText.contains("能否") ||
                processedText.contains("可以")) {
            return true;
        }

        return false;
    }

    /**
     * 预处理文本，清理和规范化
     */
    private String preprocessText(String text) {
        if (text == null) {
            return "";
        }

        String originalText = text; // 保存原始文本用于日志
        String result = text;

        // 1. 移除Markdown格式标记（如**加粗**）
        result = result.replaceAll("\\*\\*([^*]+)\\*\\*", "$1");

        // 2. 移除标题格式标记（如 # 标题）
        result = result.replaceAll("^\\s*#+\\s*", "");

        // 3. 移除列表标记（如 - 项目 或 * 项目）
        result = result.replaceAll("^\\s*[-*+]\\s+", "");

        // 4. 移除连续的特殊字符（如 ---###）
        result = result.replaceAll("[-_=*#]{3,}", "");

        // 5. 移除多余的空格
        result = result.trim().replaceAll("\\s+", " ");

        // 6. 移除控制字符
        result = result.replaceAll("[\\p{Cntrl}]", "");

        // 7. 规范化中文标点符号
        result = normalizePunctuation(result);

        log.debug("预处理前后文本对比 - 原文本: {}, 处理后: {}", originalText, result);

        return result;
    }

    /**
     * 规范化标点符号
     */
    private String normalizePunctuation(String text) {
        if (text == null) {
            return "";
        }

        // 将全角标点替换为半角（可选）
        // 保留必要的中文标点符号，如：，。！？；："'()【】《》「」

        return text;
    }
}

